import { CurrencyPipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STRequestOptions, STChange, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFSelectWidgetSchema, SFSchemaEnum } from '@delon/form';
import { dateTimePickerUtil } from '@delon/util';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { TicketService } from '../../services/ticket.service';
import { PushInvoiceComponent } from './push-invoice/push-invoice.component';

@Component({
  selector: 'app-cancellation-invoice',
  templateUrl: './cancellation-invoice.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class CancellationInvoiceComponent extends BasicTableComponent {
  @ViewChild('requestedModal', { static: false })
  requestedModal!: any;
  columns: STColumn[] = this.initST();
  schema: SFSchema = this.initSF();
  resourceStatus: any = '';

  selectedRows: any[] = [];
  totalCallNo = 0;

  openInfo: any = { invoicedate: null, invoiceno: null, invoiceno2: null };
  constructor(
    public service: TicketService,
    private nzModalService: NzModalService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value
      });
      if (this.sf?.value.createTime) {
        Object.assign(requestOptions.body, {
          createTime: {
            start: this.sf?.value.createTime?.[0] || '',
            end: this.sf?.value.createTime?.[1] || ''
          }
        });
      }
    }
    if (this.resourceStatus) {
      Object.assign(requestOptions.body, {
        sts: this.resourceStatus
      });
    } else {
      delete requestOptions.body.sts;
    }
    return requestOptions;
  };

  afterRes = (data: any[], rawData?: any) => {
    return data.map(node => ({ ...node, disabled: node.sts === '3' }));
  };

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.vatmoney, 0).toFixed(2);
        break;
    }
  }

  selectChange(e: any) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }

  /**
   * 手工开票
   * @param item
   */
  requestedAction(item: any) {
    this.openInfo = { invoicedate: null, invoiceno: null, invoiceno2: null };
    this.service.request(this.service.$api_get_apply_fico_info, { id: item.vatappHId }).subscribe(info => {
      if (info) {
        Object.assign(this.openInfo, { ...info });
        const modal = this.nzModalService.create({
          nzTitle: '发票确认',
          nzContent: this.requestedModal,
          nzOnOk: () => {
            if (!this.openInfo?.invoicedate || !this.openInfo?.invoiceno) {
              this.service.msgSrv.warning('请填开票信息');
              return false;
            }
            const params = {
              invoiceno: this.openInfo.invoiceno,
              invoicedate: dateTimePickerUtil.format(this.openInfo.invoicedate),
              invoiceno2: this.openInfo.invoiceno2
            };
            this.service
              .request(this.service.$api_apply_fico_invoic, {
                id: item.id,
                vatinvcode: item.vatinvcode,
                ...params
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('开票成功');
                  this.st.load(1);
                  modal.destroy();
                }
              });

            return false;
          }
        });
      }
    });
  }

  /**
   * 批量推送发票
   */
  batchPush() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择推送开票单');
      return;
    }
    if (this.selectedRows.find(item => item.sts !== '1')) {
      this.service.msgSrv.warning('请勿选择非待处理申请');
      return;
    }
    this.nzModalService.warning({
      nzTitle: '确定将所选待处理开票申请推送开票？',
      nzContent: '推送开票后发票信息不可修改，待系统开票完成后会自动返回开票结果',
      nzOnOk: () => {
        this.service
          .request(
            this.service.$api_batch_push_invoic,
            this.selectedRows.map(row => row.id)
          )
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('推送开票成功');
              this.st.load(1);
            }
          });
      }
    });
  }

  /**
   * 撤回
   * @param item
   * @returns
   */
  batchWithdraw(item?: any) {
    if (this.selectedRows?.length <= 0 && !item) {
      this.service.msgSrv.warning('请选择开票申请');
      return;
    }
    this.nzModalService.warning({
      nzTitle: '确定将所选待确认开票申请撤回？',
      nzContent: '提交税控后发票信息不可修改，待税控开票完成后返回开票结果',
      nzOnOk: () => {}
    });
  }

  /**
   * 移除
   * @returns
   */
  batchRemove() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择开票申请');
      return;
    }
    this.nzModalService.warning({
      nzTitle: '确定将所选待确认开票申请撤回？',
      nzContent: '提交税控后发票信息不可修改，待税控开票完成后返回开票结果',
      nzOnOk: () => {}
    });
  }

  /**
   * 作废发票
   * @param item
   * @returns
   */
  removeInvocie(item?: any) {
    const modal = this.nzModalService.warning({
      nzTitle: '确定将所选已确认开票申请作废？',
      nzContent: '作废后发票信息不可修改',
      nzOnOk: () => {
        this.service.request(this.service.$api_cancel_invoic, { id: item.id }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('发票作废成功');
            this.st.load(1);
            modal.destroy();
          }
        });
        return false;
      }
    });
  }

  downLoadDetail(item: any) {
    this.service.exportStart({ id: item.id }, this.service.$api_export_invoic_detail);
  }

  /**
   * 推送发票
   * @param item
   */
  pushInvoiceAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '推送开票',
      nzContent: PushInvoiceComponent,
      nzComponentParams: { id: item.vatappHId },
      nzWidth: 1200,
      nzOnOk: () => {
        this.service.request(this.service.$api_push_invoic, { id: item.id }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('推送开票成功');
            this.st.load(1);
          }
        });
        return false;
      }
    });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        vatappHCode: {
          type: 'string',
          title: '申请编号',
          ui: {
            placeholder: '请输入'
          }
        },
        arto: {
          type: 'string',
          title: '购买人',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => this.service.getEnterpriceList({ enterpriseName: q })
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          }
        },
        // sts: {
        //   title: '发票状态',
        //   type: 'string',
        //   ui: {
        //     widget: 'dict-select',
        //     containsAllLabel: true,
        //     params: { dictKey: 'vatinv:status' },
        //     containAllLable: true
        //   } as SFSelectWidgetSchema
        // },
        // or2derSn: {
        //   type: 'string',
        //   title: '订单号',
        //   ui: {
        //     placeholder: '请输入',
        //     visibleIf: {
        //       expand: (value: boolean) => value
        //     }
        //   }
        // },
        createTime: {
          title: '申请时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox', fixed: 'left', width: 50, className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '分票编号', render: 'vatinvcode', width: 220 },
      {
        title: '申请编号',
        index: 'vatappHCode',
        width: 220,
        type: 'link',
        click: item => this.router.navigate(['/ticket/invoice-requested/detail/' + item?.vatappHId])
      },
      { title: '申请时间', index: 'createTime', type: 'date', width: 150 },
      { title: '发票类型', index: 'vatapptypeLabel', width: 150 },
      { title: '网络货运人', index: 'ltdName', width: 220 },
      { title: '购买人', index: 'artoname', width: 220 },
      { title: '订单数', index: 'ordlines', width: 90, className: 'text-right' },
      {
        title: '价税合计',
        index: 'vatmoney',
        width: 140,
        type: 'widget',
        className: 'text-right font-weight-bold',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.vatmoney }) }
      },
      {
        title: '金额',
        index: 'vatnotax',
        width: 140,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.vatnotax }) }
      },
      // {
      //   title: '税率',
      //   index: 'billvatrate',
      //   width: 120,
      //   className: 'text-right',
      //   format: item => `${item.billvatrate ? ((item.billvatrate as number) * 100).toFixed(2) : 0}%`
      // },
      {
        title: '税额',
        index: 'vattax',
        width: 140,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.vattax }) }
      },
      { title: '服务名称', index: 'vatname', width: 120 },
      { title: '销货清单', index: 'isdetail', width: 120, type: 'enum', enum: { 1: '是', 0: '否' }, className: 'text-center' },
      { title: '票面备注', index: 'remarks', width: 300 },
      { title: '其他要求', index: 'otherremarks', width: 100 },
      {
        title: '操作',
        width: '120px',
        fixed: 'right',
        className: 'text-center',
        buttons: [
          { type: 'divider' },
          {
            text: '查看明细<br>',
            acl: { ability: ['TICKET-CANCELLATION-view'] },
            click: item =>
              this.router.navigate(['ticket/cancellation-invoice/detail/' + item.id], {
                queryParams: { type: 1, expressno: item.expressno, ltdId: item.shipperId }
              })
          },
          {
            text: '销货清单<br>',
            acl: { ability: ['TICKET-CANCELLATION-downLoadDetail'] },
            iif: item => item.isdetail,
            click: item => this.downLoadDetail(item)
          },
          {
            text: '手工开票<br>',
            acl: { ability: ['TICKET-CANCELLATION-apply'] },
            iif: item => item.sts != '3' && item.sts != '4',
            click: item => this.requestedAction(item)
          }
          // {
          //   text: '推送开票<br>',
          //   iif: item => item.sts === '1',
          //   click: item => this.pushInvoiceAction(item)
          // }
          // {
          //   text: '作废发票',
          //   iif: item => item.sts === '3',
          //   click: item => this.removeInvocie(item)
          // }
          // {
          //   text: '确认'
          //   // click: item => this.rejectAction(item)
          // },
          // {
          //   text: '撤回',
          //   click: item => this.batchWithdraw(item)
          // }
        ]
      }
    ];
  }
}
